﻿///<author>Arjen van Zanten</author>
///<datecreated>2012-03-27</datecreated>
///<summary>A class that creates and holds a grayscale histogram.</summary>

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Drawing;
using System.Drawing.Imaging;

namespace KentekenHerkenning
{
    public class GrayscaleHistogram
    {
        int[] array;
        
        /// <summary>
        /// Returns an int array holding the histogram. The element index represents the bin number, the int values represent the bin values.
        /// </summary>
        public int[] Array
        {
            get { return array; }
        }

        /// <summary>
        /// Creates an instance of the GrayscaleHistogram object.
        /// </summary>
        /// <param name="bmp">input Bitmap</param>
        public GrayscaleHistogram(Bitmap bmp) : this(bmp, 256) { }

        /// <summary>
        /// Creates an instance of the GrayscaleHistogram object.
        /// </summary>
        /// <param name="bmp">input Bitmap</param>
        /// <param name="bins">number of bins</param>
        public GrayscaleHistogram(Bitmap bmp, int bins)
        {
            array = new int[bins];

            BitmapData bmd = bmp.LockBits(new Rectangle(0, 0, bmp.Width, bmp.Height), ImageLockMode.ReadOnly, PixelFormat.Format32bppArgb);

            unsafe
            {
                byte* p = (byte*)bmd.Scan0;

                int Bpp = bmd.Stride / bmd.Width;
                int totalBytes = bmd.Width * bmd.Height * Bpp;
                int bin;

                for (int i = 0; i < totalBytes; i += Bpp)
                {
                    bin = (int)(p[i] * 0.11 + p[i + 1] * 0.59 + p[i + 2] * 0.3) * bins / 256;
                    array[bin]++;
                }
            }

            bmp.UnlockBits(bmd);
        }
    }
}
